package com.ddy.test.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by ddy on 2020/6/23 3:54 PM
 *
 * https://segmentfault.com/a/1190000019636625?utm_source=tag-newest
 *
 */

public class NioServerThreadDemo {

    private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 10, 0, TimeUnit.MILLISECONDS, new LinkedTransferQueue<>(), new ThreadPoolExecutor.AbortPolicy());

    private static Selector selector;

    public static void main(String[] args) {

        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(1234));

            selector = Selector.open();

            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            while (true){
                int select = selector.select();
                System.out.println("left " + select + " channel");

                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    if(key.isAcceptable()){
                        accept(key);
                    }else if(key.isReadable()){
                        threadPoolExecutor.submit(new NioServerHandler(key));
                    }
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void accept(SelectionKey key) {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        try {
            SocketChannel socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(false);

            socketChannel.register(selector, SelectionKey.OP_READ);
            System.out.println("client is coming: " + socketChannel.socket().getInetAddress().getHostName() + ":" + socketChannel.socket().getPort());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class NioServerHandler implements Runnable {

        private SelectionKey selectionKey;

        public NioServerHandler(SelectionKey key) {
            this.selectionKey = key;
        }

        @Override
        public void run() {
            if(selectionKey.isReadable()){
                SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                ByteBuffer byteBuffer =  ByteBuffer.allocate(4096);

                try {
                    socketChannel.read(byteBuffer);
                    byteBuffer.flip();

                    System.out.println("received data: " + new String(byteBuffer.array()));
//                    selectionKey.cancel();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
